package com._520it.crm.realm;

import com._520it.crm.domain.Employee;
import com._520it.crm.domain.Role;
import com._520it.crm.service.IEmployeeService;
import com._520it.crm.service.IPermissionService;
import com._520it.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 呆 on 2017/10/8.
 */
public class UserRealm  extends AuthorizingRealm{
    @Setter
    private IEmployeeService employeeService;
    @Setter
    private IRoleService roleService;
    @Setter
    private IPermissionService permissionService;

    public String getName(){
        return "UserRealm";
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String  username = (String) token.getPrincipal();
        System.out.println(username);
        Employee employee =  employeeService.queryByName(username);
        if (employee==null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee,employee.getPassword(),getName());
        return info;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        Employee employee = (Employee) principal.getPrimaryPrincipal();
        List<String> roles = null;
        List<String> perms = null;
        if(employee.getAdmin()==Employee.ADMIN_yes){
            List<Role> roleList = roleService.selectAll();
            roles = new ArrayList<>();
            for (Role role : roleList) {
                roles.add(role.getSn());
            }
            perms = new ArrayList<>();
            perms.add("*:*");
        }else {

            roles = roleService.queryRoleSnByEmpId(employee.getId());
            perms = permissionService.queryPermissionsByEmpId(employee.getId());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perms);
        info.addRoles(roles);
        return info;
    }


}
